package com.bestv.search.engine.servlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Servlet implementation class for Servlet: EcpDispatchServlet
 */
public final class DispatchServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    static final long serialVersionUID = 1L;
    protected final Log log = LogFactory.getLog(getClass());
    private ServletContext application;
    private WebApplicationContext wac;

    public DispatchServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        myExecute(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        myExecute(request, response);
    }

    public void init() throws ServletException {
        application = getServletContext();
        wac = WebApplicationContextUtils.getWebApplicationContext(application);
        super.init();
    }

    public void myExecute(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        String result = "";
        String requestJson = request.getParameter("q");
        log.info(requestJson);
        try {
            JSONObject jo = new JSONObject(requestJson);
            String cmd = jo.getString("cmd");
            log.debug("cmd:" + cmd);
            Object command = wac.getBean(cmd);

            Method method = null;
            if ("index".equals(cmd)) {
                method = command.getClass().getDeclaredMethod("index", String.class);
                result = (String) method.invoke(command, "");
            } else if ("search".equals(cmd)) {
                method = command.getClass().getDeclaredMethod("search", String.class);
                result = (String) method.invoke(command, requestJson);
            } else if ("similar".equals(cmd)) {
                method = command.getClass().getDeclaredMethod("similarSearch", String.class);
                result = (String) method.invoke(command, requestJson);
            } else
                log.debug("wrong command args!!");
        } catch (JSONException e1) {
            log.error(e1);
            result = "[jsonWrong]";
        } catch (Exception e) {
            e.printStackTrace();
            result = "[error]";
        }
        response.getWriter().write(result);
    }
}